<!--
 * @Author: [yuantongxin]
 * @Date: 2021-10-21 14:24:44
 * @LastEditors: [yuantongxin]
 * @LastEditTime: 2021-10-25 18:42:14
 * @Description: 
-->
<template>
  <div style="padding: 20px">
    <!-- 按钮开始 -->
    <div>
      <el-button type="primary" size="small" @click="toAdd">添加</el-button>
    </div>
    <!-- 按钮结束 -->
    <!-- 表格开始 -->
    <div>
      <!-- {{tableData}} -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="id" label="栏目编号" width="250">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="250">
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="250">
          <template slot-scope="scope">
            <div>
              <el-popover placement="right" trigger="hover">
                <el-image
                  slot="reference"
                  style="width: 50px; height: 50px"
                  :src="scope.row.icon"
                >
                </el-image>
                <el-image
                  style="width: 200px; height: 200px"
                  :src="scope.row.icon"
                ></el-image>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="排序号" width="200">
        </el-table-column>
        <!-- <el-table-column label="操作" width="260"> </el-table-column> -->
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="toDelete(scope.row.id)" style="color:#e65f70" icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->
    <!-- 分页开始 -->
    <div style="text-align: right; margin: 5px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 分页结束 -->
    <!-- 模态框开始 -->
    <div>
      <el-dialog :title="title" :visible.sync="visible">
        <el-form :model="form" :rules="rules" ref="myForm">
          <el-form-item
            label="栏目名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="序号" :label-width="formLabelWidth">
            <el-input v-model="form.num" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="form.icon" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSubmit('myForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 模态框结束 -->
  </div>
</template>

<script>
import { showFileURL, uploadFileURL } from "@/utils/config";
import { pageQuery, saveOrUpdate, deleteById } from "@/api/column";

export default {
  data() {
    return {
      // 校验表单
      rules: {
        name: [
          { required: true, message: "请输入栏目名称", trigger: "blur" },
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        icon: [
          { required: true, message: "请上传栏目图标", trigger: "blur" },
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },

      imageUrl: "",
      // 图片显示的基础路径
      showFileURL,
      // 文件上传的路径
      uploadFileURL,
      // 双向数据绑定
      form: {},
      // 表单控件的宽度
      formLabelWidth: "80px",
      // 表格绑定的数据
      tableData: [],
      // 模态框title变量
      title: "",
      // 控制模态框显示与隐藏
      visible: false,
      total: 0,
      params: {
        page: 1,
        pageSize: 5,
      },
    };
  },
  watch: {
    params: {
      handler() {
        this.queryPage();
      },
      deep: true,
    },
  },
  created() {
    this.queryPage();
  },
  methods: {
    // 删除按钮绑定事件
    toDelete(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteById({ id });
          this.queryPage();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    
    toSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await saveOrUpdate(this.form);
          this.visible = false;
          console.log(res);
          this.$message({
            message: res.message,
            type: "success"
          });
          // 刷新页面
          this.queryPage();
          // alert("submit!");
        } else {
          this.$message.error('保存失败');
          return false;
        }
      });
    },

    // async toSubmit() {

    // },
    toEdit(row) {
      this.visible = true;
      this.title = "修改栏目信息";
      this.form = { ...row };
      this.imageUrl = this.form.icon;
    },
    // 给添加按钮绑定事件
    toAdd() {
      this.visible = true;
      this.title = "添加栏目信息";
      this.form = {};
      this.imageUrl = ''
    },
    // 分页数据查询
    async queryPage() {
      let temp = {
        ...this.params,
      };
      let res = await pageQuery(temp);
      // console.log(temp);
      // console.log(res);

      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    //  处理每页显示的条数
    handleSizeChange(pageSize) {
      // console.log(`每页 ${pageSize} 条`);
      this.params.pageSize = pageSize;
      // this.queryPage()
    },
    // 处理当前页
    handleCurrentChange(page) {
      // console.log(`当前页: ${page}`);
      this.params.page = page;
      // this.queryPage()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);
      //
      this.form.icon = showFileURL + res.data.id;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang='scss' scoped>
</style>